<?php
declare (strict_types = 1);

namespace app\api\model;

use think\Model;

/**
 * @mixin \think\Model
 */
class Agent extends Model
{
    //
    /** 根据id查询所有下级信息
     * @param $parentId
     * @return array
     */
    public function getChildrenID($parentId): array
    {
        // 查询所有分类
        $agents = $this->select()->toArray();
        // 初始化结果数组
        $result = [$parentId];

        // 定义递归函数
        $this->findChildrenID($agents, $parentId, $result);

        return $result;
    }
    /**
     * 递归查找下级分类
     *
     * @param array $categories 所有分类
     * @param int $parentId 当前父级ID
     * @param array &$result 结果数组
     */
    private function findChildrenID(array $categories, int $parentId, array &$result)
    {
        foreach ($categories as $category) {
            if ($category['parent_id'] == $parentId) {
                $result[] = $category['id'];
                // 递归查找下级
                $this->findChildrenID($categories, $category['id'], $result);
            }
        }
    }
    // 递归获取所有下级分类
    public static function getSubCategories($parentId)
    {
        $result = self::where('parent_id', $parentId)->select();

        $subCategories = [];
        foreach ($result as $category) {
            $subCategories[] = $category->toArray();
            // 递归获取更深层次的子分类
            $subCategories = array_merge($subCategories, self::getSubCategories($category->id));
        }

        return $subCategories;
    }
}
